package com.news.servlet;

import com.news.service.UserService;
import com.news.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/resetPasswordServlet")
public class ResetPasswordServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");

            String username = request.getParameter("username");
            String newPassword = request.getParameter("newPassword");
            String confirmPassword = request.getParameter("confirmPassword");

            if (!newPassword.equals(confirmPassword)) {
                request.setAttribute("message", "两次输入的密码不一致");
                request.getRequestDispatcher("forgot-password.jsp").forward(request, response);
                return;
            }

            String message = userService.resetPassword(username, newPassword);
            
            if (message == null) {
                // 重置成功，设置提示信息并重定向到登录页面
                HttpSession session = request.getSession();
                session.setAttribute("message", "密码重置成功！请使用新密码登录");
                response.sendRedirect("login.jsp");
            } else {
                request.setAttribute("message", message);
                request.getRequestDispatcher("forgot-password.jsp").forward(request, response);
            }
        } catch (Exception e) {
            request.setAttribute("message", "密码重置失败：" + e.getMessage());
            request.getRequestDispatcher("forgot-password.jsp").forward(request, response);
        }
    }
} 